<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>加载百度地图</title>
    <link rel="stylesheet" href="../v6.4.3/css/ol.css">
  </head>
  <body>
    <div id="map" style="height: 500px;"></div>
    <label>Shape type &nbsp;</label>
    <select name="" id="type">
      <option value="">Select</option>
      <option value="Point">Point</option>
      <option value="LineString">LineString</option>
      <option value="Polygon">Polygon</option>
      <option value="Circle">Circle</option>
      <option value="Square">Square</option>
      <option value="Box">Box</option>
      <option value="None">None</option>
    </select>
    <script src="../v6.4.3/build/ol.js"></script>
    <script>
      // DOM对象变量
      let typeSelect = document.getElementById('type')
      
      //画图的Layer
      let vectorSource = new ol.source.Vector()
      let vectorLayer = new ol.layer.Vector({
        source: vectorSource
      })

      let draw
      function addInteraction() {
        let type = typeSelect.value;
        if (type && type !== 'None') {
          let geometryFunction;
          switch (type) {
            case 'Square':
              type = 'Circle';
              geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
              break;
            case 'Box':
              type = 'Circle';
              geometryFunction = ol.interaction.Draw.createBox();
              break;
          }
          //初始化绘图控件
          draw = new ol.interaction.Draw({
            source: vectorSource,
            type: type,
            geometryFunction: geometryFunction
          })
          map.addInteraction(draw)
        }
      }

      // 事件绑定
      typeSelect.addEventListener('change', () => {
        map.removeInteraction(draw)
        addInteraction()
      })

      // 百度地图图层
      // xc mark: 有问题，位置其实不对: 因为OpenLayers的分辨率与百度在线瓦片地图使用的分辨率对不上
      var baiduMapLayer = new ol.layer.Tile({
        source: new ol.source.XYZ({
          tilePixelRatio: 2,
          tileUrlFunction: function(tileCoord) {
            console.log(tileCoord)
            let z = tileCoord[0]
            let x = tileCoord[1]
            let y = tileCoord[2]
            console.warn(`x=${x} y=${y} z=${z}`)
            //计算当前层级下X或Y方向上瓦片总数的一半，用于定位整个地图的中心点
            let halfTileNum = Math.pow(2, z) / 2
            // let baiduX = x - halfTileNum
            // let baiduY = y + halfTileNum

            //xc觉得有问题，自己来
            let baiduX = x - halfTileNum
            let baiduY = halfTileNum - y
            //百度瓦片服务url将负数使用M前缀来标识
            if(baiduX < 0) {
              baiduX = 'M' + (-baiduX)
            }
            if(baiduY < 0) {
              baiduY = 'M' + (-baiduY)
            }
            console.log(`halfTileNum=${halfTileNum} baiduX=${baiduX} baiduY=${baiduY} z=${z}`)
            //返回经过转换后的，对应于百度在线瓦片的url
            return 'http://online2.map.bdimg.com/onlinelabel/?qt=tile&x=' + baiduX + '&y=' + baiduY + '&z=' + z + '&styles=pl&udt=20160321&scaler=2&p=0'
            // return 'http://online2.map.bdimg.com/onlinelabel/?qt=tile&x=' + x + '&y=' + y + '&z=' + z + '&styles=pl&udt=20160321&scaler=2&p=0'
          }
        })
      })

      console.error(ol.proj.fromLonLat([104.06, 30.67]))
      
      const map = new ol.Map({
        target: 'map',
        layers: [
          baiduMapLayer, vectorLayer
        ],
        view: new ol.View({
          projection: 'EPSG:3857',
          //ol.proj.formLonLat: transforms a coordinate from longitude/latitude to a different projection.
          //第一个参数为经纬度，第二个参数为 module:ol/proj-ProjectionLike. 默认为 EPSG:3857
          center: ol.proj.fromLonLat([113.23, 23.23]), //104.06, 30.67
          // center: ol.proj.fromLonLat([0, 0]),
          zoom: 10
        }),
        controls: ol.control.defaults().extend([
          new ol.control.ZoomSlider(), //滑块缩放控件
          new ol.control.FullScreen(), //全屏控件
          new ol.control.MousePosition(), //坐标拾取控件
        ])
      })
    </script>
  </body>
</html>
